package my.jessyan.mvpart.mvp.model;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Function;
import io.rx_cache2.DynamicKey;
import io.rx_cache2.EvictProvider;
import me.jessyan.art.mvp.IModel;
import me.jessyan.art.mvp.IRepositoryManager;
import my.jessyan.mvpart.mvp.model.api.cache.CommonCache;
import my.jessyan.mvpart.mvp.model.api.service.UserService;


import java.util.List;

public class MainRepository implements IModel {

    private IRepositoryManager mManager;
    public static final int PER_PAGE = 100;

    public MainRepository(IRepositoryManager mManager) {
        this.mManager = mManager;
    }

    public Observable<List<User>> getUsers(int lastIdQueried, boolean update) {
        return Observable.just(mManager
            .createRetrofitService(UserService.class)
            .getUsers(lastIdQueried, PER_PAGE))
            .flatMap(new Function<Observable<List<User>>, ObservableSource<List<User>>>() {
                @Override
                public ObservableSource<List<User>> apply(@NonNull Observable<List<User>> listObservable) throws Exception {
                    return mManager.createCacheService(CommonCache.class)
                            .getUsers(listObservable
                                    , new DynamicKey(lastIdQueried)
                                    , new EvictProvider(update))
                            .map(listReply -> listReply.getData());
                }
            });
    }

    @Override
    public void onDestroy() {

    }
}
